package com.ruoyi.web.controller.store.plan;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.RestaurantStoreResource;
import com.ruoyi.common.core.domain.entity.StorePlan;
import com.ruoyi.common.core.domain.entity.StorePlanDetail;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.mapper.RestaurantStoreResourceMapper;
import com.ruoyi.system.service.RestaurantStoreResourceService;
import com.ruoyi.system.service.StorePlanDetailService;
import com.ruoyi.system.service.StorePlanService;
import com.ruoyi.system.service.resp.StorePlanDetailDTO;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: ruohao
 * @Date: 2023/9/17
 **/
@RestController
@RequestMapping("/store/plan/detail")
public class PlanDetailController extends BaseController {
    @Resource
    private StorePlanDetailService storePlanDetailService;

    @Resource
    StorePlanService storePlanService;
    @Resource
    private RestaurantStoreResourceMapper restaurantStoreResourceMapper;

    @Resource
    RestaurantStoreResourceMapper storeResourceMapper;

    @Resource
    private RestaurantStoreResourceService restaurantStoreResourceService;

    @ApiModelProperty("获取所有请购单")
    @GetMapping("/getAllPlanList")
    public AjaxResult getAllPlanList(StorePlan storePlan) {
//        startPage();
        List<StorePlan> list = storePlanService.getAllPlanList(storePlan);
//        return getDataTable(list);
        return AjaxResult.success(list);
    }

    //点餐和正常
    @ApiModelProperty("获取所有请购单")
    @GetMapping("/getPlanList")
    public AjaxResult getPlanList(StorePlan storePlan) {
//        startPage();
        storePlan.setArea(SecurityUtils.getUserLocation());
        if(StringUtils.isNotBlank(storePlan.getArea()) && storePlan.getArea().equals("全部")){
            storePlan.setArea(null);
        }
        List<StorePlan> list = storePlanService.getPlanList(storePlan);
//        return getDataTable(list);
        return AjaxResult.success(list);
    }

    @Log(title = "查询人员管理", businessType = BusinessType.OTHER)
    @GetMapping("/list")
    public TableDataInfo list(StorePlanDetail storePlanDetail) {
        startPage();
        List<StorePlanDetail> list = storePlanDetailService.selectList(storePlanDetail);
        return getDataTable(list);
    }

    @Log(title = "查询人员管理All", businessType = BusinessType.OTHER)
    @GetMapping("/listAll")
    public TableDataInfo listAll(StorePlanDetail storePlanDetail) {
        List<StorePlanDetail> list = storePlanDetailService.selectList(storePlanDetail);
        return getDataTable(fillToDTO(list));
    }

    @GetMapping("/export")
    @ApiOperation("导出明细")
    public AjaxResult export(StorePlanDetail storePlanDetail) {
        List<StorePlanDetail> list = storePlanDetailService.selectList(storePlanDetail);
        List<StorePlanDetailDTO> exList = fillToDTO(list);
        ExcelUtil<StorePlanDetailDTO> util = new ExcelUtil<StorePlanDetailDTO>(StorePlanDetailDTO.class);
        return util.exportExcel(exList, "planDetail");
    }

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(storePlanDetailService.selectById(id));
    }

    @Log(title = "新增人员管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody StorePlanDetail storePlanDetail) {
        storePlanDetail.setUnit(storeResourceMapper.getUnit(storePlanDetail.getResourceId()));
        storePlanDetail.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = storePlanDetailService.create(storePlanDetail);
        if (result) {
            return success();
        }
        return error();
    }

    @Log(title = "修改人员管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody StorePlanDetail storePlanDetail) {
        storePlanDetail.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = storePlanDetailService.update(storePlanDetail);
        if (result) {
            if ("是".equals(storePlanDetail.getStatus())) {
                if (storePlanDetail.getResourceId() == null
                        || storePlanDetail.getAmount() == null
                        || storePlanDetail.getAmount().compareTo(BigDecimal.ZERO) == 0
                        || StringUtils.isBlank(storePlanDetail.getUnit())) {
                    return success();
                }
                RestaurantStoreResource resource = restaurantStoreResourceMapper.selectRestaurantStoreResourceById(storePlanDetail.getResourceId());
                if (resource == null) {
                    return success();
                }
                if (resource.getAmount() == null) {
                    resource.setAmount(0);
                }
                RestaurantStoreResource resourceupdate = RestaurantStoreResource.builder()
                        .id(resource.getId())
                        .amount(resource.getAmount() + storePlanDetail.getAmount().intValue())
                        .unit(storePlanDetail.getUnit()).build();
                restaurantStoreResourceMapper.updateRestaurantStoreResource(resourceupdate);
            }
            return success();
        }
        return error();
    }

    @Log(title = "删除采购计划明细", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        return toAjax(storePlanDetailService.deleteById(id));
    }

    private List<StorePlanDetailDTO> fillToDTO(List<StorePlanDetail> storePlanDetails) {
        if (CollectionUtils.isEmpty(storePlanDetails)) {
            return Collections.emptyList();
        }
        List<Long> resourceIds = storePlanDetails.stream().filter(Objects::nonNull).map(StorePlanDetail::getResourceId).collect(Collectors.toList());
        List<RestaurantStoreResource> restaurantStoreResources = restaurantStoreResourceService.selectRestaurantStoreResourceByIds(resourceIds);
        Map<Long, RestaurantStoreResource> resourceMap;
        if (CollectionUtils.isEmpty(restaurantStoreResources)) {
            resourceMap = new HashMap<>();
        } else {
            resourceMap = restaurantStoreResources.stream().collect(Collectors.toMap(RestaurantStoreResource::getId, r -> r));
        }
        return storePlanDetails.stream().filter(Objects::nonNull).map(s -> {
            StorePlanDetailDTO storePlanDetailDTO = new StorePlanDetailDTO();
            storePlanDetailDTO.setId(s.getId());
            storePlanDetailDTO.setPlanId(s.getPlanId());
            storePlanDetailDTO.setResourceId(s.getResourceId());
            storePlanDetailDTO.setResourceName(Optional.ofNullable(resourceMap.get(s.getResourceId())).map(RestaurantStoreResource::getName).orElse(null));
            storePlanDetailDTO.setAmount(s.getAmount());
            storePlanDetailDTO.setUnit(s.getUnit());
            storePlanDetailDTO.setStatus(s.getStatus());
            storePlanDetailDTO.setCreateBy(s.getCreateBy());
            storePlanDetailDTO.setCreateTime(s.getCreateTime());
            storePlanDetailDTO.setUpdateBy(s.getUpdateBy());
            storePlanDetailDTO.setUpdateTime(s.getUpdateTime());
            storePlanDetailDTO.setRemark(s.getRemark());
            return storePlanDetailDTO;
        }).collect(Collectors.toList());
    }
}
